package com.infitecs.eyas.power;

import com.infitecs.eyas.common.ajax.DataTablesPage;
import com.infitecs.eyas.common.ajax.DataTablesResponse;
import com.infitecs.eyas.constant.Constant;
import com.infitecs.eyas.power.model.Power;
import com.infitecs.eyas.power.service.PowerService;
import com.infitecs.eyas.security.model.User;
import com.infitecs.eyas.security.service.UserService;
import com.infitecs.eyas.session.SessionService;
import com.infitecs.eyas.step.modal.StepInfo;
import com.infitecs.krill.ajax.response.AjaxResponse;
import com.infitecs.krill.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by pzw on 2015/4/25.
 */
@Controller
@Transactional
@RequestMapping("/power/")
public class PowerController {

    @Autowired
    private PowerService powerService;

    @Autowired
    private UserService userService;

    @Autowired
    private SessionService sessionService;

    @RequestMapping("power")
    public String power(HttpServletRequest request) {
        List<Power> powers = powerService.getAllPower();
        List<User> users = userService.getUserList();
        request.setAttribute("users",users);
        request.setAttribute("powers", powers);
        return "quality/power";
    }

    @RequestMapping("getPowerListPage")
    @ResponseBody
    public DataTablesResponse getPowerListPage(DataTablesPage page,Power power,HttpSession session) {
        User user = (User) session.getAttribute("user");
        power.setUserId(user.getUserId());
        if (user.isAdmin()) {
            power.setUserId("");
        }
        List<Power> list=powerService.getPowerListPage(page,power);
        for(Power power1:list){
            String[] userIds=power1.getUserIds().split(",");
            String createId=  userIds[userIds.length-1];
            power1.setCreateId(createId);
            if(userService.getUser(createId)==null){
                power1.setCreateName("");
                continue;
            }
            power1.setCreateName(userService.getUser(createId).getUsername());
         }
        return new DataTablesResponse(page,list);
    }

    @RequestMapping(value = "addPower", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResponse addPower(@RequestBody @Valid Power power, BindingResult result, HttpSession session) {
        if (result.hasErrors()) {
            return new AjaxResponse(result);
        }
        User user = (User)session.getAttribute("user");
        String userIds = power.getUserIds() + "," + user.getUserId();
        power.setUserIds(userIds);
        boolean addPowerAll = powerService.addPower(power);
//        boolean update = powerService.addCaseId(power.getPowerCaseId());
        sessionService.setPowerIdAndCaseId(power);
        return AjaxResponse.getInstanceByResult(addPowerAll, session);
    }

    @RequestMapping(value = "getCaseById", method = RequestMethod.POST)
    @ResponseBody
    public List<Power> getCaseById(@RequestParam("id") int id) {
        return powerService.getAllCase(id);
    }

    @RequestMapping(value = "addCase", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResponse addCase(@RequestBody @Valid Power power, BindingResult result, HttpSession session) {
        if (result.hasErrors()) {
            return new AjaxResponse(result);
        }
        User user = (User) session.getAttribute("user");
        power.setCreateTime(DateUtil.getDateTime());
        power.setUserIds(getUserIds(power.getTempUserIds(),user));
        boolean add = powerService.addCase(power);
//        boolean update = powerService.addCaseId(power.getPowerCaseId());
        sessionService.setPowerIdAndCaseId(power);
        return AjaxResponse.getInstanceByResult(add , session);
    }

    @RequestMapping(value = "editCase", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResponse editCase(@RequestBody @Valid Power power, BindingResult result, HttpSession session) {
        if (result.hasErrors()) {
            return new AjaxResponse(result);
        }
        powerService.editCaseName(power);
        return AjaxResponse.getInstanceByResult(true, session);
    }

    private String getUserIds(List<String> userId,User user) {
        StringBuilder stringBuilder = new StringBuilder();
        if (null == userId) {
            userId = new ArrayList<>();
        }
        for (String str : userId) {
            stringBuilder.append(str).append(",");
        }
        stringBuilder.append(user.getUserId());
        return stringBuilder.toString();
    }

    @RequestMapping("openPower")
    public String openPower(@RequestParam("caseId") String caseId) {
        sessionService.setPowerIdAndCaseId(caseId);
        return "redirect:/quality/industry?menuId=8";
    }

    @RequestMapping("addPowerTrue")
    public String addPowerTrue(HttpSession session) {
        session.setAttribute("addTrue", Constant.ADD_TRUE);
        return "redirect:/quality/industry?menuId=8";
    }

    @RequestMapping(value = "finishStep", method = RequestMethod.POST)
    @ResponseBody
    public void finishStep(StepInfo stepInfo) {
        sessionService.finishStep(stepInfo);
    }

    @RequestMapping(value = "checkPowerName",method = RequestMethod.POST)
    @ResponseBody
    public boolean checkPowerName(Power power,HttpSession session) {
        User user = (User)session.getAttribute("user");
        power.setPowerName(power.getPowerName() + "-" + user.getUsername());
        int count = powerService.countPowerByName(power);
        if (count == 1) {
            return  false;
        } else {
            return true;
        }
    }

    @RequestMapping(value = "checkPowerCase",method = RequestMethod.POST)
    @ResponseBody
    public boolean checkPowerCase(Power power) {
        int count = powerService.countPowerByCase(power);
        if (count == 1) {
            return false;
        } else {
            return true;
        }
    }

    @RequestMapping(value = "checkPowerIdCase", method = RequestMethod.POST)
    @ResponseBody
    public boolean checkPowerIdCase(Power power) {
        int count = powerService.countPowerCaseName(power);
        if (count == 1) {
            return false;
        } else {
            return true;
        }
    }

    @RequestMapping("delCase")
    @ResponseBody
    public AjaxResponse delCase(@RequestParam("id") String id,HttpSession session) {
        return AjaxResponse.getInstanceByResult(powerService.delCase(id),session);
    }

    @RequestMapping(value = "addPowerOnly",method = RequestMethod.POST)
    @ResponseBody
    public Power addPowerOnly(Power power,HttpSession session) {
        User user = (User) session.getAttribute("user");
        power.setPowerName(power.getPowerName() + "-" + user.getUsername());
        return powerService.addOnlyPower(power);
    }

    @RequestMapping("getUserIds")
    @ResponseBody
    public List<String> getUserIds(@RequestParam("caseId") String caseId) {
        return powerService.getUserIds(caseId);
    }

    @RequestMapping(value = "updateShare", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResponse updateShare(@RequestBody Power power,HttpSession session) {
        User user = (User) session.getAttribute("user");
        power.setCreateTime(DateUtil.getDateTime());
        power.setUserIds(getUserIds(power.getTempUserIds(),user));
        return AjaxResponse.getInstanceByResult(powerService.updteShareUserIds(power),session);
    }

}
